/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.velocityme.session;

import com.velocityme.entity.Action;
import com.velocityme.entity.ChangeDelta;
import com.velocityme.enums.ChangeDeltaType;
import com.velocityme.enums.Permission;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 *
 * @author rcrida
 */
@Stateless
public class ActionBean implements ActionLocal {
    @EJB
    private ActivityLocal activityBean;

    @PersistenceContext
    private EntityManager em;
    
    public Action findAction(KeyLocal key, Long actionId) {
        Action action = em.find(Action.class, actionId);
        key.assertHasPermission(action, Permission.NODE_VIEW);
        return action;
    }

    public Action createAction(KeyLocal key, Action action, boolean interested) {
        key.assertHasPermission(action.getParentNode(), Permission.ACTION_CREATE);
        ChangeDelta changeDelta = action.addChangeDelta(ChangeDeltaType.CREATE, key.getUser());
        activityBean.logCreate(key, action, changeDelta, interested);
        em.persist(action);
        em.persist(changeDelta);
        return action;
    }

    public void editAction(KeyLocal key, Action action) {
        Action current = em.find(Action.class, action.getId());
        key.assertHasPermission(action, Permission.ACTION_EDIT);
        ChangeDelta changeDelta = action.addChangeDelta(ChangeDeltaType.EDIT, key.getUser());
        activityBean.logEdit(key, action, current, changeDelta);
        em.merge(action);
        em.persist(changeDelta);
    }
    
}
